import React, { useEffect, useState } from 'react';
import { Button, Tooltip } from 'antd';
import _ from 'lodash';

import { CaretLeftOutlined, CaretRightOutlined, InfoCircleOutlined } from '#/utils/antdIcons.js';
import { TjChart, TJModel, TjTable } from '@/pages/ETrade/components';
import reviewSvg from '@/assets/datang/review_analyse.svg';
import { useRem } from '@/hooks';
import { PageLoading, TRDefault } from '@/components';
import { getReviewAnalysisDesc } from '@/pages/GanSuDaTang/ProvinceSpotsReplay/services';
import {
  Doubel_yAxis_serise,
  Doubel_yAxis_title,
} from '@/pages/GanSuDaTang/ProvinceSpotsReplay/components/DayContent/helper';
import { weekChartsMap, weekColumns, weekIndexMap } from '../helper';
import styles from '../index.less';

export const WeekContent = ({ loading, dataSource = [], getAnalysisParams }) => {
  useRem(1920);

  const [isFullScreenEcharts, setIsFullScreenEcharts] = useState(false); // 是否为图表全屏展示

  const [isFullScreenTable, setIsFullScreenTable] = useState(false); // 是否为表格全屏展示

  const [realData, setRealData] = useState({}); // 记录echars数据

  const [visible, setVisible] = useState(false);

  const [info, setInfo] = useState('');

  useEffect(() => {
    if (!dataSource.length || loading) return;
    getEcharsData();
  }, [dataSource, loading]);

  const getXaxis = (data, name) => {
    const newValue = [];
    data?.map((item) => {
      if (item.id) {
        newValue.push(item[name]);
      }
    });
    return newValue;
  };

  const getPriceAverage = (arr) => {
    return arr.map((i) => {
      // 总上网电量
      // const totalOngridQuantity = i.totalOngridQuantity || 0;
      // 上网电价(含税)
      const ongridTaxPrice = i.ongridTaxPrice || 0;
      return ongridTaxPrice;
    });
  };

  const getEcharsData = () => {
    const data = dataSource.slice(1) || []; // 表格原始数据
    const dataMap = {};
    let XAXIS; // 图标X轴方向数据
    XAXIS = getXaxis(data, 'stationName');
    const flatMap = Object.values(weekChartsMap)
      .flat()
      .map((t) => t.split('_')[0])
      .filter((t) => t); //去除空字符串
    new Set(flatMap).map((t) => {
      dataMap[t] = data.map((i) => i[t]);
    });
    //计算
    dataMap._averagePrice = getPriceAverage(data); // 价格均线
    setRealData({
      ...dataMap,
      XAXIS,
    });
  };

  const getClassName = () => {
    let classNameEcharts = styles.charts;
    let classNameTable = styles.table;
    if (isFullScreenEcharts) {
      classNameEcharts = `${styles.charts} ${styles.chartsFullWidth}`;
      classNameTable = `${styles.table} ${styles.tableNoWidth}`;
    } else if (isFullScreenTable) {
      classNameEcharts = `${styles.charts} ${styles.chartsNoWidth}`;
      classNameTable = `${styles.table} ${styles.tableFullWidth}`;
    }

    return {
      classNameEcharts,
      classNameTable,
    };
  };

  const dataAnalysis = async () => {
    if (dataSource.length !== 0) {
      const res = await getReviewAnalysisDesc(getAnalysisParams());
      if (res.statusCode === '1000') {
        setInfo(res.data);
      }
      setVisible(true);
    }
  };

  const modelCancel = () => {
    setVisible(false);
  };

  /**图表配置*/
  const getChartOption = ([title, data], dataSource) => {
    const chartData = [],
      _yAxis = [{ type: 'value' }];
    dataSource.XAXIS.map((x, i) => {
      const temp = {};
      data.map((t) => {
        const a = t.split('_');
        //屏蔽同名 不同系列名
        if (a[0] && a[1]) {
          temp[t] = dataSource[a[0]][i];
          return;
        }
        temp[t] = dataSource[t][i];
      });
      chartData.push({
        ...temp,
        XAXIS: x,
      });
    });
    if (Doubel_yAxis_title.includes(title)) {
      _yAxis.push({
        type: 'value',
        splitLine: { show: false },
      });
    }
    const _series = data.map((t) => {
      const { props, ...others } = _.cloneDeep(weekIndexMap[t]);
      if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
        props.yAxisIndex = 1;
      }
      return {
        dataIndex: t,
        props,
        ...others,
      };
    });

    return {
      grid: { top: 20, left: 48, right: 36, bottom: 50 },
      series: _series,
      dataset: {
        source: chartData,
        dimensions: ['XAXIS', ...data],
      },
      tooltip: {},
      legend: {},
      xAxis: [{ type: 'category' }],
      yAxis: _yAxis,
    };
  };

  const _getEchartsData = () => {
    const loopData = Object.entries(weekChartsMap);
    if (!realData?.XAXIS) return <TRDefault type={'empty'} />;
    return (
      <div className={styles.chartsRender}>
        {loopData.map((t, i) => {
          return (
            <div
              key={i}
              style={{
                height: `calc(${Math.floor(100 / loopData.length)}%)`,
                minHeight: 204,
              }}
            >
              <div className={styles.chartTitle}>{t[0]}</div>
              <div style={{ height: `calc(100% - 30px)` }}>
                <TjChart group="A" option={getChartOption(t, realData)} />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  if (loading) return <PageLoading />;
  return (
    <>
      <div className={styles.content}>
        <div className={getClassName().classNameEcharts}>
          {_getEchartsData()}
          <div
            className={styles.leftArrow}
            onClick={() => {
              setIsFullScreenEcharts(!isFullScreenEcharts);
            }}
          >
            {isFullScreenEcharts ? <CaretLeftOutlined /> : <CaretRightOutlined />}
          </div>
        </div>
        <div className={getClassName().classNameTable}>
          <div
            className={styles.rightArrow}
            onClick={() => {
              setIsFullScreenTable(!isFullScreenTable);
            }}
          >
            {isFullScreenTable ? <CaretRightOutlined /> : <CaretLeftOutlined />}
          </div>
          <div className={styles.tableScroll}>
            <div className={styles.box1}>
              <div className={styles.hint}>
                <h3>现货交易周报</h3>
                <Tooltip
                  placement={'bottomLeft'}
                  title={
                    <div>
                      <div>
                        1.上表中，无特别说明，价格、收入均为含税电价，变动成本不含税。中长期合约电量包括代购市场电量和中长期合约电量。
                      </div>
                      <div>
                        2.其他收入包括调频收入、成本补贴、启停补偿费用等（不含新能源补贴），此为含税收入。
                      </div>
                      <div>3.火电、水电统计到公司，风电、光伏统计到类别即可。</div>
                    </div>
                  }
                >
                  <InfoCircleOutlined style={{ color: '#2978FB' }} className={styles.tooltip} />
                </Tooltip>
              </div>
              <Button
                style={{ padding: 0, color: '#18A0FB', display: 'flex', alignItems: 'center' }}
                type="link"
                icon={<img src={reviewSvg} alt={''} style={{ marginRight: 4 }} />}
                onClick={_.debounce(dataAnalysis, 500)}
              >
                复盘分析
              </Button>
            </div>
            <div className={styles.tableScroll}>
              {dataSource.length > 0 ? (
                <TjTable
                  style={{ marginLeft: '24px' }}
                  dataSource={dataSource}
                  columns={weekColumns.map((i) => ({
                    ...i,
                    align: 'center',
                    width: i.width || 100,
                  }))}
                  primaryKey={'id'}
                />
              ) : (
                <TRDefault type="empty" />
              )}
            </div>
            <TJModel
              visible={visible}
              title={'复盘分析'}
              width={400}
              onCancel={modelCancel}
              onOk={modelCancel}
            >
              <pre style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>{info}</pre>
            </TJModel>
          </div>
        </div>
      </div>
    </>
  );
};
